<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow" style="margin-top: 15px">
        <div>
          <a-form size="small" :model="pageData" layout="inline" :rules="rules" ref="searchRef">
            <a-form-item field="value2" label="客户名称">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading3"
                                    @search="handleSearch3" v-model="pageData.kehumingcheng" :filter-option="false"
                                    allow-clear allow-search @focus="focusSel3">
                                    <a-option v-for="item in pageData.kehumingchenglist" :value="item">{{ item }}</a-option>
                                </a-select> -->
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.kehumingcheng"
                @press-enter="huiche"
              />
            </a-form-item>

            <a-form-item field="value3" label="坯布编号">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading"
                                    @search="handleSearch1" v-model="pageData.pibubianhao" :filter-option="false"
                                    allow-clear allow-search @focus="focusSel1">
                                    <a-option v-for="item in pageData.pibubianhaolist" :value="item">{{ item }}</a-option>
                                </a-select> -->
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.pibubianhao"
                @press-enter="huiche"
              />
            </a-form-item>

            <a-form-item field="value1" label="坯布名称">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading2"
                                    @search="handleSearch2" v-model="pageData.pibumingcheng" :filter-option="false"
                                    allow-clear allow-search @focus="focusSel2">
                                    <a-option v-for="item in pageData.pibumingchenglist" :value="item">{{ item }}</a-option>
                                </a-select> -->
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.pibumingcheng"
                @press-enter="huiche"
              />
            </a-form-item>

            <a-form-item field="jianyanriqi" label="日期">
              <a-date-picker
                popup-container="html"
                @press-enter="huiche"
                :style="{ width: '200px' }"
                class="bacClass"
                v-model="pageData.jianyanriqi"
              />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-divisders">
          <Toolbar
            :items="pageData.btnList"
            @select="selectHandler"
            @export="exports"
            @exportAll="exportAll"
            @fhzy="fhzy"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <!-- <div class="my-tool-bar">
                    <Toolbar class="gesture" :items="pageData.btnList"  @select="selectHandler"
                        @export="exports"  @fhzy="fhzy">
                    </Toolbar>
                </div> -->
    </template>
    <template #pageTabel>
      <!--
                            表格插件
                        -->
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: 100%"
          :defaultColDef="defaultColDef"
          :suppressCopyRowsToClipboard="true"
          class="ag-theme-alpine"
          :rowData="table.dataList"
          :columnDefs="tc"
          :localeText="localeText1"
          @FilterChanged="FilterChangeds"
        >
        </AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys
      :page-size-options="pagingList1"
      :total="total"
      :page-size="size"
      :current="page"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
    />
    <a-drawer
      style="z-index: 999"
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :ok-loading="pageData.pageLoading"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item
            label-col-flex="80px"
            label="编号"
            field="brandCode"
            :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input
              class="bacClass"
              placeholder=""
              v-model="dataForm.brandCode"
              @blur="inputBlur"
            />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="品牌名称"
            field="brandName"
            :rules="[{ required: true, message: '品牌名称必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="" v-model="dataForm.brandName" />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="布类类型"
            field="clothClass"
            :rules="[{ required: true, message: '布类类型必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              :loading="loading"
              placeholder=""
              @search="handleSearch1"
              v-model="dataForm.clothClass"
              :filter-option="false"
              allow-search
              allow-clear
              @focus="focusSel1"
            >
              <a-option v-for="item in pageData.typeList" :value="item">{{ item }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="备注" field="remark">
            <!-- <a-input v-model="dataForm.remark" /> -->
            <a-textarea
              class="bacClass"
              v-model="dataForm.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post, get } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import emitter from '@/hooks/useEventBus'
  import { ref, reactive, onMounted, toRefs } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Button, Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import { baseURL } from '../../api/axios.config'
  import axios from 'axios'
  import filedownload from 'js-file-download'
  import usePermission from '@/store/modules/permission'
  import PageTabelLayout from '@/components/pageTabelLayout.vue'
  import MyTable from '@/components/MyTable'
  import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
  import { template } from 'lodash'
  import { setupGlobalComponent } from '@/layouts'
  import { localeText } from '@/api/aggridZw'
  // 引入
  
  import { stringify } from 'qs'
  import { pagingList } from '@/api/paging'
  interface BrandInfo {
    id: any
    brandCode: string
    brandName: string
    clothClass: string
    remark: string
    deleteState: number | string
    createName: string
    createTime: string
    updateName: string
    updateTime: string
  }

  export default {
    name: 'GreyDay',

    setup(props: any, { emit }) {
      const total = ref(0)
      const page = ref(1)
      const size = ref(10)
      const rules = reactive({
        jianyanriqi: [{ required: true, message: '检验日期必填' }],
      })
      const searchRef = ref<any>(null)
      function PageSize(val: any) {
        page.value = val
        doRefresh()
      }
      function change1(val: any) {
        size.value = val
        doRefresh()
      }
      const headerShow = ref<boolean>(true)

      function doRefresh() {
        pageData.pageLoading = true
        post({
          url: 'wms/report/getGreyDayInfo',
          data: {
            page:
              pageData.kehumingcheng || pageData.pibubianhao || pageData.pibumingcheng
                ? 1
                : page.value,
            size: size.value,
            greyCode: pageData.pibubianhao,
            greyName: pageData.pibumingcheng,
            customName: pageData.kehumingcheng,
            date: pageData.jianyanriqi,
          },
        })
          .then(async ({ data, code }: any) => {
            if (code === 200) {
              gridOption.value.setFilterModel(null)
              // 查询方法改
              gridOption.value.setRowData(data.list)
              total.value = data.total
              var shengchanjincangpishu = 0
              var shengchanjincangzhongliang = 0
              var qitajincangpishu = 0
              var qitajincangzhongliang = 0
              var faranchucangpishu = 0
              var faranchucangzhongliang = 0
              var qitachucangpishu = 0
              var qitachuacngzhongliang = 0
              var jiecunpishu = 0
              var jiecunzhongliang = 0
              data.data.forEach((item: any) => {
                shengchanjincangpishu += Number(item.nowIntoNum)
                shengchanjincangzhongliang += Number(item.nowIntoWeight)
                qitajincangpishu += Number(item.otherIntoNum)
                qitajincangzhongliang += Number(item.otherIntoWeight)
                faranchucangpishu += Number(item.nowOutNum)
                faranchucangzhongliang += Number(item.nowOutWeight)
                qitachucangpishu += Number(item.otherOutNum)
                qitachuacngzhongliang += Number(item.otherOutWeight)
                jiecunpishu += Number(item.nowNum)
                jiecunzhongliang += Number(item.nowWeight)
              })
              var newRows = [
                {
                  customerName: '',
                  grayCode: '',
                  grayName: '',
                  lastNum: '',
                  lastWeight: '',
                  nowIntoNum: shengchanjincangpishu.toFixed(2),
                  nowIntoWeight: shengchanjincangzhongliang.toFixed(2),
                  otherIntoNum: qitajincangpishu.toFixed(2),
                  otherIntoWeight: qitajincangzhongliang.toFixed(2),
                  nowOutNum: faranchucangpishu.toFixed(2),
                  nowOutNumWeight: faranchucangzhongliang.toFixed(2),
                  otherOutNum: qitachucangpishu.toFixed(2),
                  otherOutWeight: qitachuacngzhongliang.toFixed(2),
                  nowNum: jiecunpishu.toFixed(2),
                  nowWeight: jiecunzhongliang.toFixed(2),
                },
              ]
              gridOption.value.setPinnedBottomRowData(newRows)
              pageData.hejishuzu = newRows as any
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }

      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      const tableColumns = useTableColumn([
        {
          title: '公司',
          key: 'firmName',
          dataIndex: 'firmName',
          width: 150,
        },
        {
          title: '客户名称',
          key: 'customName',
          dataIndex: 'customName',
          width: 150,
        },

        {
          title: '坯布编号',
          key: 'greyCode',
          dataIndex: 'greyCode',
          width: 200,
        },
        {
          title: '坯布名称',
          key: 'greyName',
          dataIndex: 'greyName',
          width: 150,
        },

        {
          title: '上期结存匹数',
          key: 'lastNum',
          dataIndex: 'lastNum',
          width: 200,
        },
        {
          title: '上期结存重量',
          key: 'lastWeight',
          dataIndex: 'lastWeight',
          width: 200,
        },
        {
          title: '生产进仓匹数',
          key: 'nowIntoNum',
          dataIndex: 'nowIntoNum',
          width: 200,
        },
        {
          title: '生产进仓重量',
          key: 'nowIntoWeight',
          dataIndex: 'nowIntoWeight',
          width: 200,
        },

        {
          title: '其它进仓匹数',
          key: 'otherIntoNum',
          dataIndex: 'otherIntoNum',
          width: 200,
        },
        {
          title: '其它进仓重量',
          key: 'otherIntoWeight',
          dataIndex: 'otherIntoWeight',
          width: 200,
        },
        {
          title: '发染出仓匹数',
          key: 'nowOutNum',
          dataIndex: 'nowOutNum',
          width: 200,
        },
        {
          title: '发染出仓重量',
          key: 'nowOutWeight',
          dataIndex: 'nowOutNumWeight',
          width: 200,
        },
        {
          title: '其它出仓匹数',
          key: 'otherOutNum',
          dataIndex: 'otherOutNum',
          width: 200,
        },
        {
          title: '其它出仓重量',
          key: 'otherOutWeight',
          dataIndex: 'otherOutWeight',
          width: 200,
        },
        {
          title: '结存匹数',
          key: 'nowNum',
          dataIndex: 'nowNum',
          width: 200,
        },
        {
          title: '结存重量',
          key: 'nowWeight',
          dataIndex: 'nowWeight',
          width: 200,
        },
        {
          title: '日期',
          key: 'recordDate',
          dataIndex: 'recordDate',
          width: 200,
        },
      ])

      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        if (o.slotName === 'act') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'

          obj['cellRenderer'] = {
            template: `<a-tag color="#ff7d00" class="gesture" v-if="e" @click="a">修改</a-tag>`,
            setup(props: any) {
              const a = () => {
                editHandler(props.params.data)
              }
              return {
                e: pageData.isEdit,
                a,
              }
            },
          }
        }

        return obj
      })

      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      const pageData = reactive<{
        showAdd: boolean
        sideTitle: string
        dropDownData: any
        nameList: []
        pageLoading: boolean
        typeList: []
        dropDownData1: any
        rHeight: any
        btnList: any[]
        isEdit: boolean
        zhizaocode: any
        hejishuzu: []
        pibubianhao: any
        pibubianhaolist: []
        pibumingcheng: any
        pibumingchenglist: []
        kehumingcheng: any
        kehumingchenglist: any[]
        jianyanriqi: any
        jitaihao: any
        jitaihaolist: []
        firmId2: any
        firmList2: []
        yuangongName: []
        yuanliaomingcheng: any
        yuanliaomingchenglist: any[]
        biaoji: any
      }>({
        nameList: [],
        showAdd: false,
        sideTitle: '新增品牌资料',
        dropDownData: '',
        pageLoading: false,
        typeList: [],
        dropDownData1: '',
        rHeight: 0,
        btnList: [],
        isEdit: false,
        zhizaocode: '',
        hejishuzu: [],
        pibubianhao: '',
        pibubianhaolist: [],
        pibumingcheng: '',
        pibumingchenglist: [],
        kehumingcheng: '',
        kehumingchenglist: [] as any,
        jianyanriqi: '',
        jitaihao: '',
        jitaihaolist: [],
        firmId2: '',
        firmList2: [],
        yuangongName: [],
        yuanliaomingcheng: '',
        yuanliaomingchenglist: [] as any,
        biaoji: 0,
      })

      interface gcType {
        id: any
        company: any
      }

      //下拉框得到焦点
      const focusSel = () => {
        selCxAll({ brandName: '', deleteState: 0 })
      }
      //下拉数据

      onMounted(() => {
        // 切换tap到本页面执行的方法
        emitter.on('BrandInfo', () => {
          // selCxAll1({});
          doRefresh()
        })
      })
      let cxbl = ''
      //查询
      const selectHandler = async () => {
        const valid = await searchRef.value.validate()
        if (valid) return
        pagination.page = 1
        cxbl = pageData.dropDownData
        doRefresh()
      }
      const queryData = reactive({
        clothType: '',
      })
      const addHandler = () => {}
      const dataForm = reactive<BrandInfo>({
        id: null,
        remark: '',
        brandName: '',
        clothClass: '',
        deleteState: '',
        createName: '',
        createTime: '',
        updateName: '',
        updateTime: '',
        brandCode: '',
      })

      // 表格准备事件
      const gridOption = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
      }

      let formRef = ref<FormInstance>()
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            formRef.value?.validate().then((err) => {
              if (!err) {
                pageData.pageLoading = true
                if (pageData.sideTitle === '新增品牌资料') {
                  post({
                    url: 'product/Brand/insert',
                    data: [dataForm],
                  })
                    .then((res: any) => {
                      if (res.code === 200) {
                        formRef.value?.resetFields()
                        pageData.showAdd = false

                        Message.success({
                          content: '新增成功',
                          duration: 5000,
                        })
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 5000,
                        })
                      }
                      doRefresh()
                    })
                    .finally(() => {
                      doRefresh()
                      pageData.pageLoading = false
                    })
                } else {
                  post({
                    url: 'product/Brand/update',
                    data: [dataForm],
                  })
                    .then((res: any) => {
                      if (res.code === 200) {
                        formRef.value?.resetFields()
                        pageData.showAdd = false
                        Message.success({
                          content: '修改成功',
                          duration: 5000,
                        })
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 5000,
                        })
                      }
                    })
                    .finally(() => {
                      doRefresh()
                      pageData.pageLoading = false
                    })
                }
              }
            })
          }
        })
      }
      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        }

        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            pageData.pageLoading = true
            post({
              url: 'product/Brand/deleteList',
              data: gridOption.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            })
              .then(({ code, data }: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })
                  pagination.page = 1
                  doRefresh()
                } else {
                  Message.error({
                    content: '删除失败',
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          },
        })
      }

      let curobj = null
      const editHandler = (record: BrandInfo) => {
        curobj = record
        selCxAll({ key: '' })
        dataForm.brandCode = record.brandCode
        dataForm.brandName = record.brandName
        dataForm.clothClass = record.clothClass
        dataForm.remark = record.remark
        dataForm.id = record.id
        pageData.sideTitle = '修改品牌资料'
        pageData.showAdd = true
      }
      //判断是否填写了中文
      const isChiese = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值不能包含中文！')
          }
          resolve()
        })
      }
      //input离开焦点 将小写转大写
      const inputBlur = () => {
        dataForm.brandCode = dataForm.brandCode.toUpperCase()
      }
      //导出
      const exports = () => {
        //
        var zongshuzu = [] as any
        gridOption.value.getSelectedRows().forEach(function (o: any) {
          zongshuzu.push(o)
        })
        pageData.hejishuzu.forEach((o: any) => {
          zongshuzu.push(o)
        })
        localStorage.setItem('daocu', JSON.stringify(zongshuzu))
        //
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        } else {
          let idList: any = []
          // gridOption.value.getSelectedRows().forEach(function(o:any){
          //     idList.push(o['id'])
          // })
          zongshuzu.forEach(function (o: any) {
            idList.push(o['id'])
          })

          //        {
          //     title: "客户名称",
          //     key: "customerName",
          //     dataIndex: "customerName",
          //     width: 150
          // },

          // {
          //     title: "坯布编号",
          //     key: "grayCode",
          //     dataIndex: "greyCode",
          //     width: 200
          // },
          // {
          //     title: "坯布名称",
          //     key: "grayName",
          //     dataIndex: "grayName",
          //     width: 150
          // },

          // {
          //     title: "上期结存匹数",
          //     key: "lastNum",
          //     dataIndex: "lastNum",
          //     width: 200
          // },
          // {
          //     title: "上期结存重量",
          //     key: "lastWeight",
          //     dataIndex: "lastWeight",
          //     width: 200
          // },
          // {
          //     title: "生产进仓匹数",
          //     key: "nowIntoNum",
          //     dataIndex: "nowIntoNum",
          //     width: 200
          // },
          // {
          //     title: "生产进仓重量",
          //     key: "nowIntoWeight",
          //     dataIndex: "nowIntoWeight",
          //     width: 200
          // },
          // {
          //     title: "其他进仓匹数",
          //     key: "otherOutNum",
          //     dataIndex: "nowOutNum",
          //     width: 200
          // },
          // {
          //
          //
          //
          //
          //
          //  {
          //     title: "其它进仓重量",
          //     key: "otherIntoWeight",
          //     dataIndex: "otherIntoWeight",
          //     width: 200
          // },
          //  {
          //     title: "发染出仓匹数",
          //     key: "nowOutNum",
          //     dataIndex: "nowOutNum",
          //     width: 200
          // },
          //  {
          //     title: "发染出仓重量",
          //     key: "nowOutWeight",
          //     dataIndex: "nowOutNumWeight",
          //     width: 200
          // },
          //  {
          //     title: "其它出仓匹数",
          //     key: "otherOutNum",
          //     dataIndex: "otherOutNum",
          //     width: 200
          // },
          //   {
          //     title: "其它出仓重量",
          //     key: "otherOutWeight",
          //     dataIndex: "nowWeight",
          //     width: 200
          // },
          //   {
          //     title: "结存匹数",
          //     key: "nowNum",
          //     dataIndex: "nowNum",
          //     width: 200
          // },
          //   {
          //     title: "结存重量",
          //     key: "nowWeight",
          //     dataIndex: "nowWeight",
          //     width: 200
          // },
          //   {
          //     title: "日期",
          //     key: "nowWeight",
          //     dataIndex: "nowWeight",
          //     width: 200
          // },

          //将表头拼接出来
          let head =
            '<th>客户名称</th><th>坯布编号</th><th>坯布名称</th><th>上期结存匹数</th><th>上期结存重量</th><th>生产进仓匹数</th><th>生产进仓重量</th><th>其他进仓匹数</th>'
          head +=
            '<th>其他进仓重量</th><th>发染出仓匹数</th><th>发染出仓重量</th><th>其他出仓匹数</th><th>其他出仓重量</th><th>结存匹数</th><th>结存重量</th>'

          //拿到当前表格数据与勾选的行做筛选

          // let nowRow = table.dataList.filter(function (o) {
          //     return (gridOption.value.getSelectedRows().map((o: any) => { return o.id })).indexOf(o["id"]) !== -1;
          // })
          let nowRow = zongshuzu.filter(function (o) {
            return (
              zongshuzu
                .map((o: any) => {
                  return o.id
                })
                .indexOf(o['id']) !== -1
            )
          })
          let body = ''
          var shengchanjincangpishu = 0
          var shengchanjincangzhongliang = 0
          var qitajincangpishu = 0
          var qitajincangzhongliang = 0
          var faranchucangpishu = 0
          var faranchucangzhongliang = 0
          var qitachucangpishu = 0
          var qitachuacngzhongliang = 0
          var jiecunpishu = 0
          var jiecunzhongliang = 0
          nowRow.forEach(function (o, index) {
            if (index != nowRow.length - 1) {
              shengchanjincangpishu = shengchanjincangpishu + o['nowIntoNum']
              shengchanjincangzhongliang = shengchanjincangzhongliang + o['nowIntoWeight']
              qitajincangpishu = qitajincangpishu + o['otherIntoNum']
              qitajincangzhongliang = qitajincangzhongliang + o['otherIntoWeight']
              faranchucangpishu = faranchucangpishu + o['otherOutNum']
              faranchucangzhongliang = faranchucangzhongliang + o['otherOutWeight']
              qitachucangpishu = qitachucangpishu + o['nowOutNum"']
              qitachuacngzhongliang = qitachuacngzhongliang + o['nowOutWeight']
              jiecunpishu = jiecunpishu + o['nowNum']
              jiecunzhongliang = jiecunzhongliang + o['nowWeight']
            } else {
              o['nowIntoNum'] = shengchanjincangpishu
              o['nowIntoWeight'] = shengchanjincangzhongliang
              o['otherIntoNum'] = qitajincangpishu
              o['otherIntoWeight'] = qitajincangzhongliang
              o['otherOutNum'] = faranchucangpishu
              o['otherOutWeight'] = faranchucangzhongliang
              o['nowOutNum"'] = qitachucangpishu
              o['nowOutWeight'] = qitachuacngzhongliang
              o['nowNum'] = jiecunpishu
              o['nowWeight'] = jiecunzhongliang
            }

            body += '<td>' + o['customName'] + '</td>'
            body += '<td>' + o['greyCode'] + '</td>'

            body += '<td>' + o['greyName'] + '</td>'
            body += '<td>' + o['lastNum'] + '</td>'
            body += '<td>' + o['lastWeight'] + '</td>'
            body += '<td>' + o['nowIntoNum'] + '</td>'
            body += '<td>' + o['nowIntoWeight'] + '</td>'
            body += '<td>' + o['otherIntoNum'] + '</td>'
            body += '<td>' + o['otherIntoWeight'] + '</td>'
            body += '<td>' + o['otherOutNum'] + '</td>'
            body += '<td>' + o['otherOutWeight'] + '</td>'
            body += '<td>' + o['nowOutNum'] + '</td>'
            body += '<td>' + o['nowOutWeight'] + '</td>'
            body += '<td>' + o['nowNum'] + '</td>'
            body += '<td>' + o['nowWeight'] + '</td>'

            body += '</tr>'
          })
          tableToXlsx(head, '坯布日报表', body)
          console.log(table)
        }
      }

      const exportAll = () => {
        post({
          url: '/wms/report/exportGetGreyDayInfo',
          data: {
            greyCode: pageData.pibubianhao,
            greyName: pageData.pibumingcheng,
            customName: pageData.kehumingcheng,
            date: pageData.jianyanriqi,
          },
          responseType: 'blob',
        }).then((res) => {
          filedownload(res, '坯布日结表.xlsx')
        })
      }
      function tableToXlsx(head: any, filename: any, body: any) {
        const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

        const a = document.createElement('a')
        a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
        a.download = filename
        a.click()
        document.removeChild(a)
      }

      //模板下载
      const downloadHandler = () => {
        axios
          .get(baseURL + '/product/Brand/uploadModel', {
            responseType: 'blob',
            headers: {
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((res) => {
            if (res.status === 200) {
              filedownload(res.data, '品牌资料.xlsx')
            }
          })
      }
      //导入
      const importHandler = () => {
        const inputEle: HTMLInputElement = document.createElement('input')
        inputEle.type = 'file'
        inputEle.id = 'fileUploadExcel'
        inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
        inputEle.addEventListener('change', (e) => {
          const formData = new FormData()
          if (inputEle.files !== null) {
            formData.append('file', inputEle.files[0] || '')
          } else {
            Message.warning('未选择文件！')
            return
          }
          pageData.pageLoading = true
          axios
            .post(baseURL + '/product/Brand/importModelData', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((result) => {
              if (result.data['code'] === 200) {
                Message.success('导入成功')
              } else {
                Message.error(result.data.message)
              }
            })
            .finally(() => {
              pageData.pageLoading = false
              doRefresh()
            })
        })
        inputEle.click()
      }
      //下拉数据
      const options = ref<any>(pageData.pibubianhaolist)
      const loading = ref(false)
      const handleSearch1 = (value: any) => {
        if (value) {
          const ob = { greyCode: value }
          loading.value = true

          selCxAll(ob)
          options.value = pageData.pibubianhaolist
          loading.value = false
        } else {
          options.value = []
        }
      }

      //下拉框查询 布料类型
      //下拉框查询 坯布编号
      function selCxAll(val: any) {
        post({
          url: 'product/Rawmaterial/getGreyDrop',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            // (data as string[]).splice(0, 0, "全部");
            pageData.pibubianhaolist = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      const options2 = ref<any>(pageData.pibumingchenglist)
      const loading2 = ref(false)
      const handleSearch2 = (value: any) => {
        if (value) {
          const ob = { grayFabricName: value }
          loading.value = true

          selCxAll2(ob)
          options.value = pageData.pibumingchenglist
          loading.value = false
        } else {
          options.value = []
        }
      }
      //下拉框查询 坯布名称
      function selCxAll2(val: any) {
        post({
          url: 'product/Rawmaterial/getGreyDrop',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            // (data as string[]).splice(0, 0, "全部");
            pageData.pibumingchenglist = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }
      const options3 = ref<any>(pageData.kehumingchenglist)
      const loading3 = ref(false)
      const handleSearch3 = (value: any) => {
        if (value) {
          const ob = { customName: value }
          loading.value = true

          selCxAll3(ob)
          options.value = pageData.kehumingchenglist
          loading.value = false
        } else {
          options.value = []
        }
      }
      function selCxAll3(val: any) {
        post({
          url: 'planSingle/planOrder/getDropInfo',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            // (data as string[]).splice(0, 0, "全部");
            //sessionStorage.setItem("kehumingccheng",JSON.stringify(data))
            //sessionStorage.setItem("iskehupp",JSON.stringify(data))

            pageData.kehumingchenglist = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      const options4 = ref<any>(pageData.jitaihaolist)
      const loading4 = ref(false)
      const handleSearch4 = (value: any) => {
        if (value) {
          const ob = { machineCode: value }
          loading.value = true

          selCxAll4(ob)
          options.value = pageData.jitaihaolist
          loading.value = false
        } else {
          options.value = []
        }
      }
      //下拉框查询 坯布名称
      function selCxAll4(val: any) {
        post({
          url: 'planSingle/machine/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            // (data as string[]).splice(0, 0, "全部");

            pageData.jitaihaolist = data
            //sessionStorage.setItem("kehumingccheng",JSON.stringify(pageData.jitaihao))
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }
      function selCxAll6(val: any) {
        pageData.biaoji = 2
        pageData.yuanliaomingchenglist = []
        post({
          url: '/wms/warehouseType/getWarehoursTypePara',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            data.forEach((o: any) => {
              var obj = { label: o.typeName, value: o.id, children: [] }
              pageData.yuanliaomingchenglist.push(obj)
            })

            pageData.yuanliaomingchenglist.forEach((d) => {
              // gongsi(d)
            })
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }
      //下拉框得到焦点
      const focusSel1 = () => {
        selCxAll({ greyCode: '' })
      }
      const focusSel2 = () => {
        selCxAll2({ grayFabricName: '' })
      }

      const focusSel3 = () => {
        selCxAll3({ customName: '' })
      }
      const focusSel4 = () => {
        selCxAll4({ machineCode: '' })
      }

      const focusSel6 = () => {
        selCxAll6({})
      }
      //设置权限
      // ['查询', '新增', '删除', '导出', '导入']
      const permissionStore = usePermission()

    
      pageData.btnList.push('查询')

      pageData.btnList.push('导出')
      pageData.btnList.push('全部导出')
   
      // if (permissionStore.hasPermisson('ppzl.dr')) {
      //   pageData.btnList.push('返回主页')
      // }
      if (permissionStore.hasPermisson('ppzl.xg')) {
        pageData.isEdit = true
      }
      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }
      const fhzy = () => {
        emit('takebiaoji', 0)
      }
      //获得公司部门组下的员工
      const getFirmGroup = () => {
        get({
          url: '/org/firmGroup/getTreeFirmGroup',
        }).then(({ code, data }) => {
          if (code === 200) {
            pageData.firmList2 = data
            huoquyuangong()
          }
        })
      }
      const huoquyuangong = () => {
        pageData.firmList2.forEach((o: any) => {
          o.children.forEach((d: any) => {
            d.children.forEach((a: any) => {
              post({
                url: 'org/employee/getList',
                data: {
                  groupId: a.value,
                  empName: '',
                },
              }).then((res) => {
                if (res.code == 200) {
                  res.data.forEach((m: any) => {
                    a.children = [{ label: m.empName, value: m.empName }]
                  })
                } else {
                  Message.error({
                    content: '查询员工名称失败',
                    duration: 5000,
                  })
                }
              })
            })
          })
        })
      }

      //获得公司
      // function gongsi(val: any) {

      //     post({
      //         url: "/org/firmGroup/getFirmInfoByMap",
      //         data: {}
      //     }).then(({ data, code }: any) => {
      //         if (code === 200) {
      //             data.map((o: any) => {
      //                 val.children.push({ label: o.firmName, value: o.id, warehouseTypeName: val.label, children: [] })

      //             })
      //             val.children.map((a: any) => {
      //                 getcangku(a);

      //             })

      //         } else {
      //             Message.error({
      //                 content: "查询失败！",
      //                 duration: 5000,
      //             });
      //         }
      //     });

      // }
      function getcangku(val: any) {
        post({
          url: '/wms/warehouse/getWarehouseByPara',
          data: { firmId: val.value, warehouseTypeName: val.warehouseTypeName, virtuallyState: 0 },
        }).then(({ data, code }: any) => {
          if (code === 200) {
            data.map((d: any) => {
              val.children.push({
                label: d.warehouseName,
                value: d.id,
                firmId: d.firmId,
                warehouseTypeName: d.warehouseTypeName,
              })
            })

            val.children.map((a: any) => {
              // getyuanliaobianhao(a);
            })
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      const huiche = () => {
        pagination.page = 1
        cxbl = pageData.dropDownData
        doRefresh()
      }
      const localeText1: any = ref(localeText)
      const pagingList1: any = ref(pagingList)
      const FilterChangeds = (params: any) => {
        let data: any = {
          data: [],
        }
        params.api.forEachNodeAfterFilter((row: any) => {
          data.data.push(row.data)
        })
        var shengchanjincangpishu = 0
        var shengchanjincangzhongliang = 0
        var qitajincangpishu = 0
        var qitajincangzhongliang = 0
        var faranchucangpishu = 0
        var faranchucangzhongliang = 0
        var qitachucangpishu = 0
        var qitachuacngzhongliang = 0
        var jiecunpishu = 0
        var jiecunzhongliang = 0
        // data.data.map((o: any) => {
        //   o.nowIntoNum = o.nowIntoNum + Number(shengchanjincangpishu)
        //   o.nowIntoWeight = o.nowIntoWeight + Number(shengchanjincangzhongliang)
        //   o.otherIntoNum = o.otherIntoNum + Number(qitajincangpishu)
        //   o.otherIntoWeight = o.otherIntoWeight + Number(qitajincangzhongliang)
        //   o.nowOutNum = o.nowOutNum + Number(faranchucangpishu)
        //   o.nowOutWeight = o.nowOutWeight + Number(faranchucangzhongliang)
        //   o.otherOutNum = o.otherOutNum + Number(qitachucangpishu)
        //   o.otherOutWeight = o.otherOutWeight + Number(qitachuacngzhongliang)
        //   o.nowNum = o.nowNum + Number(jiecunpishu)
        //   o.nowWeight = o.nowWeight + Number(jiecunzhongliang)
        // })
        data.data.forEach((item: any) => {
          shengchanjincangpishu += Number(item.nowIntoNum)
          shengchanjincangzhongliang += Number(item.nowIntoWeight)
          qitajincangpishu += Number(item.otherIntoNum)
          qitajincangzhongliang += Number(item.otherIntoWeight)
          faranchucangpishu += Number(item.nowOutNum)
          faranchucangzhongliang += Number(item.nowOutWeight)
          qitachucangpishu += Number(item.otherOutNum)
          qitachuacngzhongliang += Number(item.otherOutWeight)
          jiecunpishu += Number(item.nowNum)
          jiecunzhongliang += Number(item.nowWeight)
        })
        var newRows = [
          {
            customerName: '',
            grayCode: '',
            grayName: '',
            lastNum: '',
            lastWeight: '',
            nowIntoNum: shengchanjincangpishu.toFixed(2),
            nowIntoWeight: shengchanjincangzhongliang.toFixed(2),
            otherIntoNum: qitajincangpishu.toFixed(2),
            otherIntoWeight: qitajincangzhongliang.toFixed(2),
            nowOutNum: faranchucangpishu.toFixed(2),
            nowOutNumWeight: faranchucangzhongliang.toFixed(2),
            otherOutNum: qitachucangpishu.toFixed(2),
            otherOutWeight: qitachuacngzhongliang.toFixed(2),
            nowNum: jiecunpishu.toFixed(2),
            nowWeight: jiecunzhongliang.toFixed(2),
          },
        ]
        gridOption.value.setPinnedBottomRowData(newRows)
      }
      return {
        FilterChangeds,
        pagingList1,
        huiche,
        localeText1,
        defaultColDef,
        tc,
        total,
        PageSize,
        change1,
        page,
        size,
        editHandler,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        selectHandler,
        isChiese,
        inputBlur,
        exports,
        exportAll,
        options,
        options2,
        options3,
        options4,
        loading,
        loading2,
        loading3,
        loading4,
        handleSearch1,
        handleSearch2,
        handleSearch3,
        handleSearch4,
        focusSel,
        downloadHandler,
        importHandler,
        focusSel1,
        focusSel2,
        focusSel3,
        focusSel4,
        focusSel6,
        headerShow,
        handleChange,
        gridReady,
        fhzy,
        selCxAll,
        getFirmGroup,
        searchRef,
        rules,
      }
    },
    props: {
      biaoji: Number,
    },
    components: { Toolbar, PageTabelLayout,  },
  }
</script>
<style scoped>
  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }

  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }
</style>
